package com.sino.androiddesign.customView


import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.os.Bundle
import android.support.v4.app.Fragment
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

import com.sino.androiddesign.R


/**
 * A simple [Fragment] subclass.
 *
 */
class Demo1PieFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_demo1_pie, container, false)
    }


}


class PieData(var value: Float, var percentage: Float, var color: Int, var angle: Float)

class PieView : View {
    constructor(context: Context) : this(context, null)
    constructor(context: Context, attributeSet: AttributeSet?) : super(context, attributeSet)

    // 颜色表(注意: 此处定义颜色使用的是ARGB，带Alpha通道的)
    private val mColors = intArrayOf(Color.RED, Color.GREEN, Color.GREEN,
            Color.YELLOW, Color.CYAN, Color.BLUE)

    private var mStartAngle: Float = 0f   //开始的角度

    private var mData: ArrayList<PieData> = ArrayList()  //对应的数据

    private var mWidth: Int = 0
    private var mHeight: Int = 0

    private val mPaint = Paint()

    private val mRectF = RectF()

    init {

        mPaint.style = Paint.Style.FILL
        mPaint.isAntiAlias = true
        println("执行init方法")
        initData()
    }


    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        println("执行onSizeChanged $w $h")
        mWidth = w
        mHeight = h

    }

    override fun onDraw(canvas: Canvas?) {

        println(mData.size)
        var currentStartAngle = mStartAngle
        canvas!!.translate(mWidth / 2.toFloat(), mHeight / 2.toFloat())
        val r = Math.min(mWidth, mHeight) / 2 * 0.8.toFloat()
        mRectF.set(-r, -r, r, r)

        for (data in mData) {
            mPaint.color = data.color
            canvas.drawArc(mRectF, currentStartAngle, data.angle, true, mPaint)
            currentStartAngle += data.angle
        }
    }

    private fun initData() {

        var sumValue = 0f

        for (i in 0 until mColors.size) {

            val value = (Math.random() * 10).toFloat()

            val testData = PieData(value, 0f, mColors[i], 0f)

            sumValue += value
            mData.add(testData)
        }

        var sumAngle = 0f

        for (i in 0 until mColors.size) {

            val pieData = mData[i]
            val percentage = pieData.value / sumValue
            val angle = percentage * 360

            pieData.percentage = percentage
            pieData.angle = angle
            sumAngle += angle
        }

    }
}
